import { defineStore } from 'pinia'
import { getToken, removeCache, setToken } from '@/utils/auth'
import { ref } from 'vue'
import { resetRouter } from '@/router'
import { profile, userLogin } from '@/api/login'
import { useMenuStore } from '@/stores/menuStore'

export const useUserStore = defineStore('user', () => {
  const menuStore = useMenuStore()
  // state
  const token = ref(getToken())
  const info = ref(null)
  const avatar = ref('https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
  // action
  const login = (userInfo) => {
    //调用登录接口
    return new Promise((resolve, reject) => {
      userLogin(userInfo)
        .then((res) => {
          //存token
          setToken(res.data)
          resolve(res)
        })
        .catch((error) => {
          console.log(error)
          reject(error)
        })
    })
  }
  // 查询用户权限
  const getUserRoles = async () => {
    return new Promise((resolve, reject) => {
      profile()
        .then((res) => {
          info.value = res.data
          menuStore.addAsyncRoutes(info.value.roles.menus)
          resolve(res.data)
        })
        .catch((error) => {
          console.log(error)
          reject(error)
        })
    })
  }
  // user logout
  const logout = () => {
    return new Promise((resolve) => {
      removeCache() // must remove  token  first
      resetRouter()
      resolve()
    })
  }

  return { token, info, avatar, login, getUserRoles, logout }
})
